import imageSrc from '../res/images/7c741de5f63c1c8be2ad38740760a739.jpg';

import { Render, ResourceTypes } from '../lib';
import { createCamera } from './camera';
import { createBox } from './graphics-utils';
import { ImageColor } from './basic-graphics-shaders';
import * as mat4 from './mat4';

const { VertexBuffers, IndexBuffer, Uniforms, Textures } = ResourceTypes;

document.body.style.width = window.innerWidth + 'px';
document.body.style.height = window.innerHeight + 'px';
document.body.style.backgroundColor = '#2d2d2d';
document.body.style.display = 'flex';
document.body.style.justifyContent = 'center';
document.body.style.alignItems = 'center';

let element = document.createElement('canvas');
element.id = 'webgl';
element.width = 640;
element.height = 640;
element.style.border = '5px solid #000000';
element.style.backgroundColor = '#3d3d3d';
document.body.appendChild(element);

let canvas = document.getElementById('webgl');

let intervalId;
let time = 0;
function runMainLoop() {
    let callback = (now) => {
        intervalId = window.requestAnimationFrame(callback);
        time = now;
        renderFunc();
    };
    intervalId = window.requestAnimationFrame(callback);
}

const render = new Render(canvas);
const shader = render.shader(ImageColor);
const cameraMats = createCamera({ eye: [10, 10, 10] });
const box = createBox();
let imageState;
let baseMat = mat4.create();
mat4.scale(baseMat, baseMat, [2, 2, 2]);

cameraMats.modelMat = baseMat;

console.log(cameraMats);

let image = new Image();
image.src = imageSrc;
image.onload = function () {
    imageState = { image, flip: true };
    runMainLoop();
};

let rad = 0;
function renderFunc() {
    rad += 0.01;
    let rotateMat = mat4.create();
    mat4.rotate(rotateMat, baseMat, rad, [0, 1, 0]);
    cameraMats.modelMat = rotateMat;
    render
        .clear()
        .draw(
            shader,
            render.resource(VertexBuffers, box.vertex),
            render.resource(IndexBuffer, box.index),
            render.resource(Uniforms, cameraMats),
            render.resource(Textures, { img: imageState })
        );
}
